package com.sentinel.client.handle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.sentinel.client.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(MyBlockExceptionHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        logger.error("全局限流异常:", e);
        String msg = "未知限流异常";
        if (e instanceof FlowException) {
            msg = "接口限流了";
        } else if (e instanceof DegradeException) {
            msg = "服务降级了";
        } else if (e instanceof ParamFlowException) {
            msg = "热点参数限流了";
        } else if (e instanceof SystemBlockException) {
            msg = "触发系统保护规则了";
        } else if (e instanceof AuthorityException) {
            msg = "授权规则不通过";
        }
        ResponseUtil.writeJson(response, msg);
    }
}